package com.hzit.controller;

import com.hzit.common.entity.R;
import com.hzit.entity.Users;
import com.hzit.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.jws.WebParam;
import java.util.ArrayList;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Controller
@RequestMapping
public class UserController {
	@Autowired
	private UsersMapper usersMapper;

	//1. 需要某个权限才能访问
	// @Secured({"ROLE_user"})              // 拥有ROLE_user角色才可访问此资源
	//@PreAuthorize("hasAuthority('adminxx')")  // 在方法执行前判断是否有指定权限
	//@PostAuthorize("hasAuthority('adminxxxx')")   // 在方法执行后再判断是否有权限
	@RequestMapping("/user/list")
	public String findAll(Model model) {
		System.out.println("user-->findAll()");
		List<Users> users = usersMapper.selectAll();
		model.addAttribute("users", users);
		return "list";
	}

	//2. 登录成功后，跳转到欢迎页面
	@RequestMapping("/user/welcome")
	public String welcome(Model model) {
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		System.out.println("principal = " + principal);
		if (principal != null) {
			User user = (User) principal;
			String username = user.getUsername();
			model.addAttribute("username", username);
		}
		return "welcome";
	}

	@GetMapping("/user/findAll")
	@ResponseBody
	@PostFilter("filterObject.username == 'bbb'") // 过滤方法返回结果中的数据，返回前过滤,其中filterObject代表返回的集合中的某一项
	public List<Users> findAll(){
		List<Users> users = new ArrayList<>();
		users.add(new Users(1,"aaa","test1111"));
		users.add(new Users(2,"bbb","test222"));
		return users;
	}

	@PostMapping("/user/findAll2")
	@ResponseBody
	@PreFilter("filterObject.username == 'aaa'") // 过滤方法参数传入之前就过滤，其中filterObject代表返回的集合中的某一项
	public List<Users> findAll2(@RequestBody List<Users> users){
		System.out.println("postAuthorize...");
		return users;
	}
}
